package com.gpframework.module.controller.ctn;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.ctn.domain.GpCtnOrder;
import com.gpframework.module.ctn.domain.GpItemTranslation;
import com.gpframework.module.ctn.domain.GpPackagesInformation;
import com.gpframework.module.ctn.domain.GpSackInformation;
import com.gpframework.module.ctn.domain.req.GpCtnOrderAdd;
import com.gpframework.module.ctn.domain.req.GpCtnOrderAddBach;
import com.gpframework.module.ctn.domain.req.GpCtnOrderReq;
import com.gpframework.module.ctn.domain.req.GpCtnOrderUpdate;
import com.gpframework.module.ctn.domain.vo.*;
import com.gpframework.module.ctn.service.*;
import com.gpframework.module.module.domain.GpAgentCompany;
import com.gpframework.module.module.service.IGpAgentCompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DateFormatSymbols;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

/**
 * @ClassName GpCtnOrderController
 * @Author gpframework
 * @Date 2024-01-08
 * @Version 1.0.0
 * @Description 定货柜填写Controller
 */
@Validated
@Api(tags = "定货柜填写")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes", "unchecked"})
@RequestMapping("/ctn/order")
public class GpCtnOrderController extends BaseController {

    private final IGpCtnOrderService iGpCtnOrderService;
    private final IGpCtnLoadedService iGpCtnLoadedService;
    private final IGpAgentCompanyService iGpAgentCompanyService;
    private final IGpCtnReachPortService iGpCtnReachPortService;
    private final IGpTelexReleaseService iGpTelexReleaseService;
    private final IGpPackagesInformationService iGpPackagesInformationService;
    private final IGpSackInformationService iGpSackInformationService;
    private final IGpItemTranslationService     iGpItemTranslationService;



    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-01-08
     * @Param gpCtnOrder
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('ctn:order:list')")
    @GetMapping("/list")
    public TableDataInfo<GpCtnOrderVo> list(GpCtnOrderReq gpCtnOrderReq) {
        startPage();
        QueryWrapper<GpCtnOrder> lqw = new QueryWrapper<GpCtnOrder>();
        gpCtnOrderReq.generatorQuery(lqw, true);
        List<GpCtnOrderVo> listVo = iGpCtnOrderService.listVo(lqw);
        for (GpCtnOrderVo gpCtnOrderVo : listVo) {
            gpCtnOrderVo.setLoadedPicturesVo(StringUtils.stringToList(gpCtnOrderVo.getLoadedPictures()));
            gpCtnOrderVo.setLoadedVideoVo(StringUtils.stringToList(gpCtnOrderVo.getLoadedVideo()));
        }
        return getDataTable(listVo);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-01-08
     * @Param gpCtnOrder
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('ctn:order:add')")
    @Log(title = "新增定货柜填写图片", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GpCtnOrderAdd gpCtnOrderAdd) {
        GpCtnOrder ctnOrder = iGpCtnOrderService.getOne(new QueryWrapper<GpCtnOrder>().eq("agent_ctn_no", gpCtnOrderAdd.getAgentCtnNo()).eq("del_status", YesNoEnum.NO.getKey()));
        GpCtnOrder gpCtnOrder = Convert.convert(new TypeReference<GpCtnOrder>() {
        }, gpCtnOrderAdd);
        if (gpCtnOrderAdd.getAgentCompanyId() != null) {
            GpAgentCompany agentCompany = iGpAgentCompanyService.getById(gpCtnOrderAdd.getAgentCompanyId());
            gpCtnOrder.setAgentCompany(agentCompany.getAgentCompany());
        }
        //新增货柜信息
        //if (gpCtnOrderAdd.getLoadedPictures() != null) {
        //    gpCtnOrder.setLoadedPictures(StringUtils.listTostring(gpCtnOrderAdd.getLoadedPictures()));
        //}
        //
        //if (gpCtnOrderAdd.getLoadedVideo() != null) {
        //    gpCtnOrder.setLoadedVideo(StringUtils.listTostring(gpCtnOrderAdd.getLoadedVideo()));
        //}
        return toAjax(iGpCtnOrderService.saveOrUpdate(gpCtnOrder) ? 1 : 0);
    }


    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-01-08
     * @Param gpCtnOrder
     * @Return TableDataInfo
     */
    @ApiOperation("修改订货柜图片")
    @PreAuthorize("@ss.hasPermi('ctn:order:edit')")
    @Log(title = "修改订货柜图片", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody GpCtnOrderUpdate gpCtnOrderUpdate) {
        GpCtnOrder gpCtnOrder = Convert.convert(new TypeReference<GpCtnOrder>() {
        }, gpCtnOrderUpdate);
        if (gpCtnOrderUpdate.getAgentCompanyId() != null) {
            GpAgentCompany agentCompany = iGpAgentCompanyService.getById(gpCtnOrderUpdate.getAgentCompanyId());
            gpCtnOrder.setAgentCompany(agentCompany.getAgentCompany());
        }


        if (gpCtnOrderUpdate.getLoadedPicturesVo()!=null){
            gpCtnOrder.setLoadedPictures(StringUtils.listTostring(gpCtnOrderUpdate.getLoadedPicturesVo()));
        }
        if (gpCtnOrderUpdate.getLoadedVideoVo()!=null){
            gpCtnOrder.setLoadedVideo(StringUtils.listTostring(gpCtnOrderUpdate.getLoadedVideoVo()));
        }
        return toAjax(iGpCtnOrderService.updateById(gpCtnOrder) ? 1 : 0);
    }



    @ApiOperation("修改订货柜")
    @PreAuthorize("@ss.hasPermi('ctn:order:edit')")
    @Log(title = "修改订货柜", businessType = BusinessType.UPDATE)
    @PutMapping("/editOrder")
    public AjaxResult editOrder(@Valid @RequestBody GpCtnOrderAddBach gpCtnOrderAddBach) {
        GpCtnOrder gpCtnOrder = Convert.convert(new TypeReference<GpCtnOrder>() {
        }, gpCtnOrderAddBach);
        if (gpCtnOrderAddBach.getAgentCompanyId() != null) {
            GpAgentCompany agentCompany = iGpAgentCompanyService.getById(gpCtnOrderAddBach.getAgentCompanyId());
            gpCtnOrder.setAgentCompany(agentCompany.getAgentCompany());
        }

        return toAjax(iGpCtnOrderService.updateById(gpCtnOrder) ? 1 : 0);
    }


    @ApiOperation("装柜录入操作")
    @PreAuthorize("@ss.hasPermi('ctn:orderLoad:edit')")
    @Log(title = "装柜录入操作", businessType = BusinessType.UPDATE)
    @PostMapping("/orderLoadList")
    public AjaxResult orderLoadList(@Valid @RequestBody GpCtnOrderUpdate gpCtnOrderUpdate) {
        if (gpCtnOrderUpdate.getGpCtnOrderList() != null) {
            iGpCtnOrderService.orderLoadList(gpCtnOrderUpdate.getGpCtnOrderList());
        }
        return AjaxResult.success();
    }


    /**
     * @Description 导出定货柜填写模板
     * @Author gpframework
     * @Date 2023-05-24
     * @Param gpCustomer
     * @Return TableDataInfo
     */
    @ApiOperation("导出定货柜填写模板")
    @Log(title = "导出定货柜填写模板", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('ctn:order:importTemplate')")
    @GetMapping("/importTemplate")
    public AjaxResult exportTemplate() {
        ExcelUtil<GpCtnOrderExcel> util = new ExcelUtil<>(GpCtnOrderExcel.class);
        return util.exportExcel(GpCtnOrderExcel.list(), "模板");
    }

    /**
     * @Description 导入定货柜填写
     * @Author gpframework
     * @Date 2023-10-27
     * @Param (GpMember
     * @Return TableDataInfo
     */
    @Log(title = "导入定货柜填写", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ctn:order:import')")
    @PostMapping("/import")
    public AjaxResult entityImport(MultipartFile file, Long brandId, Long storeId) throws Exception {
        ExcelUtil<GpCtnOrderExcel> util = new ExcelUtil<GpCtnOrderExcel>(GpCtnOrderExcel.class);
        List<GpCtnOrderExcel> excelList = util.importExcel(file.getInputStream());

        return AjaxResult.builder(() -> {
            return this.iGpCtnOrderService.gpCtnOrderImport(excelList, brandId, storeId);
        });
    }

    @PreAuthorize("@ss.hasPermi('ctn:order:export')")
    @Log(title = "导出装货柜清单", businessType = BusinessType.EXPORT)
    @ApiOperation("导出装货柜清单")
    @GetMapping("/export")
    public AjaxResult export(GpCtnOrderReq gpCtnOrderReq) throws Exception, IOException {
        QueryWrapper<GpCtnOrder> lqw = new QueryWrapper<GpCtnOrder>();
        gpCtnOrderReq.generatorQuery(lqw, true);
        List<GpCtnOrderVo> list = iGpCtnOrderService.listVo(lqw);

        List<GpPackagesInformationExcel> informationExcels = new ArrayList<>();
        CtnLoadListTemplate ctnLoadListTemplate = new CtnLoadListTemplate();
        BigDecimal total = new BigDecimal("0");
        BigDecimal totalSack = new BigDecimal("0");
        Set<String> packNoSets = new HashSet<>();
        HashSet<String> notDuplicateList = new HashSet<>();

        for (GpCtnOrderVo gpCtnOrderVo : list) {
            if (gpCtnOrderVo != null) {
                List<GpPackagesInformationVo> gpPackagesInformationVos = iGpPackagesInformationService.listVo(new QueryWrapper<GpPackagesInformation>().eq("ctn_order_id", gpCtnOrderVo.getId()).eq("del_status", YesNoEnum.NO));
                List<GpSackInformationVo> gpSackInformationVos = iGpSackInformationService.listVo(new QueryWrapper<GpSackInformation>().eq("ctn_order_id", gpCtnOrderVo.getId()).eq("del_status", YesNoEnum.NO));

                if (gpPackagesInformationVos != null) {
                    for (GpPackagesInformationVo gpPackagesInformationVo : gpPackagesInformationVos) {
                        GpPackagesInformationExcel gpPackagesInformationExcel = new GpPackagesInformationExcel();
                        gpPackagesInformationExcel.setCustomer(gpPackagesInformationVo.getCustomer() + "-" + gpPackagesInformationVo.getPackNo());

                        //翻译item
                        GpItemTranslation gpItemTranslation = iGpItemTranslationService.getOne(new LambdaQueryWrapper<GpItemTranslation>().eq(GpItemTranslation::getChineseItem, gpPackagesInformationVo.getGoodsDescription()).eq(GpItemTranslation::getDelStatus, YesNoEnum.NO.getKey()));
                        if (gpItemTranslation==null){
                            gpPackagesInformationExcel.setGoodsDescription(gpPackagesInformationVo.getGoodsDescription() + "-" + gpPackagesInformationVo.getPackNo());
                        }
                        if (gpItemTranslation!=null && gpItemTranslation.getEnglishItem()!=null){
                            gpPackagesInformationExcel.setGoodsDescription(gpItemTranslation.getEnglishItem() + "-" + gpPackagesInformationVo.getPackNo());

                        }
                        //cbm去除尾部零
                        String cbmNoZero = new BigDecimal(gpPackagesInformationVo.getCbm()).stripTrailingZeros().toPlainString();
                        gpPackagesInformationExcel.setCbm(cbmNoZero + "-" + gpPackagesInformationVo.getPackNo());

                        if (!gpPackagesInformationVo.getCustomerTel().isEmpty()){
                            // 获取第一个字符并检查是否为数字
                            char firstDigit  = gpPackagesInformationVo.getCustomerTel().charAt(0);
                            if (Character.isDigit(firstDigit)){
                                if (firstDigit == '1') {
                                    //电话号码的第一个数字是1 +keep
                                    gpPackagesInformationExcel.setCustomerTel("keep"+gpPackagesInformationVo.getCustomerTel()+ "-" + gpPackagesInformationVo.getCustomer());
                                } else {
                                    gpPackagesInformationExcel.setCustomerTel(gpPackagesInformationVo.getCustomerTel()+ "-" + gpPackagesInformationVo.getCustomer());
                                }
                            } else {
                                throw new BaseException("电话号码的第一个字符不是数字");
                            }
                        }

                        gpPackagesInformationExcel.setPackNo(gpPackagesInformationVo.getPackNo());
                        gpPackagesInformationExcel.setPackagesNum(gpPackagesInformationVo.getPackagesNum());
                        gpPackagesInformationExcel.setReceiptNo(gpPackagesInformationVo.getReceiptNo());

                        //数包数
                        if (gpPackagesInformationExcel.getPackNo()!=null){
                            String s = gpPackagesInformationExcel.getPackNo() + gpPackagesInformationExcel.getCbm();
                            packNoSets.add(s);
                            if (!notDuplicateList.contains(s)) {
                                String[] cbm = gpPackagesInformationExcel.getCbm().split("-");
                                total = total.add(new BigDecimal(cbm[0]));
                            }
                            notDuplicateList.add(s);
                        }

                        informationExcels.add(gpPackagesInformationExcel);
                    }
                }

                if (gpSackInformationVos != null) {
                    for (GpSackInformationVo gpSackInformationVo : gpSackInformationVos) {
                        GpSackInformationExcel gpSackInformationExcel = new GpSackInformationExcel();

                        gpSackInformationExcel.setCustomer(gpSackInformationVo.getCustomer());
                        //翻译item
                        GpItemTranslation gpItemTranslation = iGpItemTranslationService.getOne(new LambdaQueryWrapper<GpItemTranslation>().eq(GpItemTranslation::getChineseItem, gpSackInformationVo.getGoodsDescription()).eq(GpItemTranslation::getDelStatus, YesNoEnum.NO.getKey()));
                        if (gpItemTranslation==null){
                            gpSackInformationExcel.setGoodsDescription(gpSackInformationVo.getGoodsDescription());
                        }
                        if (gpItemTranslation!=null && gpItemTranslation.getEnglishItem()!=null){
                            gpSackInformationExcel.setGoodsDescription(gpItemTranslation.getEnglishItem());
                        }
                        gpSackInformationExcel.setCbm(gpSackInformationVo.getCbm());
                        if (!gpSackInformationVo.getCustomerTel().isEmpty()){
                            // 获取第一个字符并检查是否为数字
                            char firstDigit  = gpSackInformationVo.getCustomerTel().charAt(0);
                            if (Character.isDigit(firstDigit)){
                                if (firstDigit == '1') {
                                    //电话号码的第一个数字是1 +keep
                                    gpSackInformationExcel.setCustomerTel("keep"+gpSackInformationVo.getCustomerTel()+ "-" + gpSackInformationVo.getCustomer());
                                } else {
                                    gpSackInformationExcel.setCustomerTel(gpSackInformationVo.getCustomerTel()+ "-" + gpSackInformationVo.getCustomer());
                                }
                            } else {
                                throw new BaseException("电话号码的第一个字符不是数字");
                            }
                        }
                        gpSackInformationExcel.setReceiptNo(gpSackInformationVo.getReceiptNo());

                        if (gpSackInformationExcel.getCbm()!=null){
                            String[] cbm = gpSackInformationExcel.getCbm().split("-");
                            totalSack = totalSack.add(new BigDecimal(cbm[0]));
                        }
                        GpPackagesInformationExcel convert = Convert.convert(new TypeReference<GpPackagesInformationExcel>() {
                        }, gpSackInformationExcel);
                        informationExcels.add(convert);
                    }

                }

            }

            ctnLoadListTemplate.setTotalCbm((total.add(totalSack)).stripTrailingZeros().toPlainString());
            ctnLoadListTemplate.setCtnNo(gpCtnOrderVo.getCtnNo());
            ctnLoadListTemplate.setBillNo(gpCtnOrderVo.getBillNo());
            ctnLoadListTemplate.setSealNo(gpCtnOrderVo.getSealNo());
            ctnLoadListTemplate.setAgentCompany(gpCtnOrderVo.getAgentCompany()+"00"+gpCtnOrderVo.getAgentCtnNo());
            ctnLoadListTemplate.setDestination(gpCtnOrderVo.getDestination());

            if (gpCtnOrderVo.getLoadedDate() != null) {
                ctnLoadListTemplate.setLoadedDate(DateUtils.parseDateToStr("dd-MM-yyyy", gpCtnOrderVo.getLoadedDate()));
            }
            if (gpCtnOrderVo.getLoadTime() != null) {
                ctnLoadListTemplate.setCtnLoadTime(DateUtils.parseDateToStr("dd-MM-yyyy", gpCtnOrderVo.getLoadTime()));
            }
        }


        InputStream inputStream = new URL("https://haihe.gpinfo.com.cn/excelTemplate/CtnLoadList.xlsx").openStream();


        String fileName = new String();
        return AjaxResult.success(iGpCtnOrderService.getString(informationExcels, ctnLoadListTemplate, inputStream, "装柜清单.xlsx").getUrl());
    }





    @PreAuthorize("@ss.hasPermi('ctn:order:export')")
    @Log(title = "导出装货柜信息", businessType = BusinessType.EXPORT)
    @ApiOperation("导出装货柜信息")
    @GetMapping("/exportMessage")
    public AjaxResult exportMessage(GpCtnOrderReq gpCtnOrderReq) throws Exception, IOException {
        QueryWrapper<GpCtnOrder> lqw = new QueryWrapper<GpCtnOrder>();
        gpCtnOrderReq.generatorQuery(lqw, true);
        List<GpCtnOrderVo> list = iGpCtnOrderService.listVo(lqw);

        List<GpPackagesSackInformationExcel> informationExcels = new ArrayList<>();
        CtnLoadListTemplate ctnLoadListTemplate = new CtnLoadListTemplate();
        BigDecimal totalPackWeight = new BigDecimal("0");
        BigDecimal totalPackCbm = new BigDecimal("0");
        BigDecimal totalSackWeight = new BigDecimal("0");
        BigDecimal totalSackCbm = new BigDecimal("0");
        Set<String> packNoSets = new HashSet<>();
        HashSet<String> notDuplicateList = new HashSet<>();
        Long numberNo = new Long("0");
        for (GpCtnOrderVo gpCtnOrderVo : list) {
            if (gpCtnOrderVo != null) {
                List<GpPackagesInformationVo> gpPackagesInformationVos = iGpPackagesInformationService.listVo(new QueryWrapper<GpPackagesInformation>().eq("ctn_order_id", gpCtnOrderVo.getId()).eq("del_status", YesNoEnum.NO));
                List<GpSackInformationVo> gpSackInformationVos = iGpSackInformationService.listVo(new QueryWrapper<GpSackInformation>().eq("ctn_order_id", gpCtnOrderVo.getId()).eq("del_status", YesNoEnum.NO));
                if (gpPackagesInformationVos != null) {
                    for (GpPackagesInformationVo gpPackagesInformationVo : gpPackagesInformationVos) {
                        GpPackagesSackInformationExcel gpPackagesInformationExcel = new GpPackagesSackInformationExcel();
                        if (gpPackagesInformationVo!=null){
                            numberNo=numberNo+1L;
                        }
                        gpPackagesInformationExcel.setNo("NO."+String.valueOf(numberNo));

                        int month = gpPackagesInformationVo.getReceiptDate().getMonth();
                        int day = gpPackagesInformationVo.getReceiptDate().getDay();
                        String monthEnglish = getEnglishMonthName(month);
                        gpPackagesInformationExcel.setReceiptDate(day+"/"+monthEnglish+"-"+gpPackagesInformationVo.getCustomer());

                        gpPackagesInformationExcel.setPackNo(gpPackagesInformationVo.getPackNo());
                        gpPackagesInformationExcel.setCustomer(gpPackagesInformationVo.getCustomer() + "-" + gpPackagesInformationVo.getPackNo());

                        //翻译item
                        GpItemTranslation gpItemTranslation = iGpItemTranslationService.getOne(new LambdaQueryWrapper<GpItemTranslation>().eq(GpItemTranslation::getChineseItem, gpPackagesInformationVo.getGoodsDescription().trim()).eq(GpItemTranslation::getDelStatus, YesNoEnum.NO.getKey()));
                        if (gpItemTranslation==null){
                            gpPackagesInformationExcel.setGoodsDescription(gpPackagesInformationVo.getGoodsDescription() + "-" + gpPackagesInformationVo.getPackNo());
                        }
                        if (gpItemTranslation!=null && gpItemTranslation.getEnglishItem()!=null){
                            gpPackagesInformationExcel.setGoodsDescription(gpItemTranslation.getEnglishItem() + "-" + gpPackagesInformationVo.getPackNo());

                        }
                        /** 入仓件数qty */
                        gpPackagesInformationExcel.setQty(String.valueOf(gpPackagesInformationVo.getWarehousedNum()));


                        //cbm去除尾部零
                        String cbmNoZero = new BigDecimal(gpPackagesInformationVo.getCbm()).stripTrailingZeros().toPlainString();
                        gpPackagesInformationExcel.setCbm(cbmNoZero + "-" + gpPackagesInformationVo.getPackNo());

                        gpPackagesInformationExcel.setWeight(gpPackagesInformationVo.getPackWeight().stripTrailingZeros().toPlainString() + "-" + gpPackagesInformationVo.getPackNo());

                        if (gpPackagesInformationVo.getHoldOrNot().equals("0")){
                            gpPackagesInformationExcel.setHoldorNot("RELEASE"+ "-" + gpPackagesInformationVo.getCustomer());
                            if (!gpPackagesInformationVo.getCustomerTel().isEmpty()){
                                // 获取第一个字符并检查是否为数字
                                char firstDigit  = gpPackagesInformationVo.getCustomerTel().charAt(0);
                                if (Character.isDigit(firstDigit)){
                                    if (firstDigit == '1') {
                                        //电话号码的第一个数字是1 +keep
                                        gpPackagesInformationExcel.setSupplierTel("keep"+gpPackagesInformationVo.getSupplierTel()+ "-" + gpPackagesInformationVo.getCustomer());
                                    } else {
                                        gpPackagesInformationExcel.setCustomerTel(gpPackagesInformationVo.getCustomerTel()+ "-" + gpPackagesInformationVo.getCustomer());
                                    }
                                } else {
                                    throw new BaseException("电话号码的第一个字符不是数字");
                                }
                            }
                        }else {
                            gpPackagesInformationExcel.setHoldorNot("HOLD"+ "-" + gpPackagesInformationVo.getCustomer());
                            //客户电话
                            if (!gpPackagesInformationVo.getSupplierTel().isEmpty()){
                                // 获取第一个字符并检查是否为数字
                                char firstDigit  = gpPackagesInformationVo.getSupplierTel().charAt(0);
                                if (Character.isDigit(firstDigit)){
                                    if (firstDigit == '0') {
                                        //电话号码的第一个数字是0 只显示 customerTel
                                        gpPackagesInformationExcel.setCustomerTel(gpPackagesInformationVo.getCustomerTel()+ "-" + gpPackagesInformationVo.getCustomer());
                                    }
                                    else {
                                        gpPackagesInformationExcel.setSupplierTel("keep"+gpPackagesInformationVo.getSupplierTel()+ "-" + gpPackagesInformationVo.getCustomer());
                                    }
                                } else {
                                    throw new BaseException("电话号码的第一个字符不是数字");
                                }
                            }
                        }
                        gpPackagesInformationExcel.setReceiptNo(gpPackagesInformationVo.getReceiptNo());

                        informationExcels.add(gpPackagesInformationExcel);


                        //数包数
                        //计算打包总计weight 打包总计cbm
                        if (gpPackagesInformationExcel.getPackNo()!=null){
                            String s = gpPackagesInformationExcel.getPackNo() + gpPackagesInformationExcel.getCbm();
                            packNoSets.add(s);
                            if (!notDuplicateList.contains(s)) {
                                String[] cbm = gpPackagesInformationExcel.getCbm().split("-");
                                String[] weight = gpPackagesInformationExcel.getWeight().split("-");
                                totalPackCbm = totalPackCbm.add(new BigDecimal(cbm[0]));
                                totalPackWeight=totalPackWeight.add(new BigDecimal(weight[0]));
                            }
                            notDuplicateList.add(s);
                        }


                    }
                    // 在末尾添加一个统计对象
                    GpPackagesSackInformationExcel last = new GpPackagesSackInformationExcel();


                    last.setCbm(totalPackCbm.stripTrailingZeros().toPlainString());
                    last.setWeight(totalPackWeight.stripTrailingZeros().toPlainString());
                    informationExcels.add(last);
                    // 在末尾添加两个空对象
                    GpPackagesSackInformationExcel end = new GpPackagesSackInformationExcel();
                    GpPackagesSackInformationExcel endend = new GpPackagesSackInformationExcel();
                    informationExcels.add(end);
                    informationExcels.add(endend);
                }

                if (gpSackInformationVos != null) {
                    // 在散货前面添加一个字段对象
                    GpPackagesSackInformationExcel midFirst = new GpPackagesSackInformationExcel();
                    midFirst.setReceiptDate("SUPPLY DATE");
                    midFirst.setPackNo(" ");
                    midFirst.setCustomer("CUSTOMER");
                    midFirst.setGoodsDescription("DEC");
                    midFirst.setQty("SACKS(PCS)");
                    midFirst.setCustomerTel("TEL");
                    midFirst.setSupplierTel("SUPPLYER");
                    midFirst.setCbm("CBM");
                    midFirst.setWeight("WEIGHT");
                    midFirst.setHoldorNot("NOTES");
                    midFirst.setReceiptNo("RECIPTE NO.");
                    informationExcels.add(midFirst);
                    for (GpSackInformationVo gpSackInformationVo : gpSackInformationVos) {
                        GpPackagesSackInformationExcel gpSackInformationExcel = new GpPackagesSackInformationExcel();


                        int month = gpSackInformationVo.getReceiptDate().getMonth();
                        int day = gpSackInformationVo.getReceiptDate().getDay();

                        String monthEnglish = getEnglishMonthName(month);

                        gpSackInformationExcel.setReceiptDate(day+"/"+monthEnglish+"-"+gpSackInformationVo.getCustomer());


                        gpSackInformationExcel.setCustomer(gpSackInformationVo.getCustomer());

                        //翻译item
                        GpItemTranslation gpItemTranslation = iGpItemTranslationService.getOne(new LambdaQueryWrapper<GpItemTranslation>().eq(GpItemTranslation::getChineseItem, gpSackInformationVo.getGoodsDescription().trim()).eq(GpItemTranslation::getDelStatus, YesNoEnum.NO.getKey()));
                        if (gpItemTranslation==null){
                            gpSackInformationExcel.setGoodsDescription(gpSackInformationVo.getGoodsDescription());
                        }
                        if (gpItemTranslation!=null && gpItemTranslation.getEnglishItem()!=null){
                            gpSackInformationExcel.setGoodsDescription(gpItemTranslation.getEnglishItem());
                        }

                        gpSackInformationExcel.setQty(gpSackInformationVo.getWarehousedNum()+"");
                        if (("包").equals(gpSackInformationVo.getUnit())){
                            gpSackInformationExcel.setQty(gpSackInformationVo.getWarehousedNum()+"SACK");
                        }

                        if (("件").equals(gpSackInformationVo.getUnit())){
                            gpSackInformationExcel.setQty(gpSackInformationVo.getWarehousedNum()+"SACK");
                        }

                        if (("箱").equals(gpSackInformationVo.getUnit())){
                            gpSackInformationExcel.setQty(gpSackInformationVo.getWarehousedNum()+"CTN");
                        }


                        if (gpSackInformationVo.getHoldOrNot().equals("0")){
                            gpSackInformationExcel.setHoldorNot("RELEASE"+ "-" + gpSackInformationVo.getCustomer());
                            if (!gpSackInformationVo.getCustomerTel().isEmpty()){
                                // 获取第一个字符并检查是否为数字
                                char firstDigit  = gpSackInformationVo.getCustomerTel().charAt(0);
                                if (Character.isDigit(firstDigit)){
                                    if (firstDigit == '1') {
                                        //电话号码的第一个数字是1 +keep
                                        gpSackInformationExcel.setSupplierTel("keep"+gpSackInformationVo.getSupplierTel()+ "-" + gpSackInformationVo.getCustomer());
                                    } else {
                                        gpSackInformationExcel.setCustomerTel(gpSackInformationVo.getCustomerTel()+ "-" + gpSackInformationVo.getCustomer());
                                    }
                                } else {
                                    throw new BaseException("电话号码的第一个字符不是数字");
                                }
                            }

                        }else {
                            gpSackInformationExcel.setHoldorNot("HOLD"+ "-" + gpSackInformationVo.getCustomer());
                            //供应商电话
                            if (!gpSackInformationVo.getSupplierTel().isEmpty()){
                                // 获取第一个字符并检查是否为数字
                                char firstDigit  = gpSackInformationVo.getSupplierTel().charAt(0);
                                if (Character.isDigit(firstDigit)){
                                    if (firstDigit == '0') {
                                        //电话号码的第一个数字是0
                                        gpSackInformationExcel.setCustomerTel(gpSackInformationVo.getCustomerTel()+ "-" + gpSackInformationVo.getCustomer());
                                    }
                                    else {
                                        gpSackInformationExcel.setSupplierTel("keep"+gpSackInformationVo.getSupplierTel()+ "-" + gpSackInformationVo.getCustomer());
                                    }

                                } else {
                                    throw new BaseException("电话号码的第一个字符不是数字");
                                }
                            }

                        }

                        //cbm去除尾部零
                        String cbmNoZero = new BigDecimal(gpSackInformationVo.getCbm()).stripTrailingZeros().toPlainString();
                        gpSackInformationExcel.setCbm(cbmNoZero);
                        gpSackInformationExcel.setWeight(gpSackInformationVo.getSackWeight().stripTrailingZeros().toPlainString());
                        gpSackInformationExcel.setReceiptNo(gpSackInformationVo.getReceiptNo());



                        //计算打包总计cbm
                        if (gpSackInformationExcel.getCbm()!=null){
                            String[] cbm = gpSackInformationExcel.getCbm().split("-");
                            totalSackCbm=totalSackCbm.add(new BigDecimal(cbm[0]));
                        }
                        //计算打包总计weight
                        if (gpSackInformationExcel.getWeight()!=null){
                            String[] weight = gpSackInformationExcel.getWeight().split("-");
                            totalSackWeight=totalSackWeight.add(new BigDecimal(weight[0]));
                        }


                        informationExcels.add(gpSackInformationExcel);
                    }

                    // 在末尾添加一个统计对象
                    GpPackagesSackInformationExcel last = new GpPackagesSackInformationExcel();
                    last.setCbm(totalSackCbm.stripTrailingZeros().toPlainString());
                    last.setWeight(totalSackWeight.stripTrailingZeros().toPlainString());
                    informationExcels.add(last);
                }

            }

            ctnLoadListTemplate.setTotalWeight((totalPackWeight.add(totalSackWeight)).stripTrailingZeros().toPlainString());
            ctnLoadListTemplate.setTotalCbm((totalPackCbm.add(totalSackCbm)).stripTrailingZeros().toPlainString());

            ctnLoadListTemplate.setCtnNo(gpCtnOrderVo.getCtnNo());
            ctnLoadListTemplate.setBillNo(gpCtnOrderVo.getBillNo());
            ctnLoadListTemplate.setSealNo(gpCtnOrderVo.getSealNo());
            ctnLoadListTemplate.setAgentCompany(gpCtnOrderVo.getAgentCompany()+"00"+gpCtnOrderVo.getAgentCtnNo());
            ctnLoadListTemplate.setDestination(gpCtnOrderVo.getDestination());

            ctnLoadListTemplate.setAgentCtnNo(DateUtils.parseDateToStr("yyyy", gpCtnOrderVo.getLoadedDate())+gpCtnOrderVo.getAgentCtnNo());


            if (gpCtnOrderVo.getLoadedDate() != null) {
                LocalDate loadedDate = gpCtnOrderVo.getLoadedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                int day = loadedDate.getDayOfMonth();
                int month = loadedDate.getMonthValue();

                ctnLoadListTemplate.setLoadedDate(day+"th-"+month+"-"+DateUtils.parseDateToStr("yyyy", gpCtnOrderVo.getLoadedDate()));
            }
            if (gpCtnOrderVo.getLoadedDate() != null) {
                ctnLoadListTemplate.setLoadedDateEnd(DateUtils.parseDateToStr("yyyy/MM/dd", gpCtnOrderVo.getLoadedDate()));
            }
            if (gpCtnOrderVo.getLoadTime() != null) {
                ctnLoadListTemplate.setCtnLoadTime(DateUtils.parseDateToStr("dd-MM-yyyy", gpCtnOrderVo.getLoadTime()));
            }
        }


        InputStream inputStream = new URL("https://haihe.gpinfo.com.cn/excelTemplate/CtnLoadPackSackList.xlsx").openStream();

        return AjaxResult.success(iGpCtnOrderService.getStringPackSack(informationExcels, ctnLoadListTemplate, inputStream, "货柜信息.xlsx").getUrl());
    }


    //获取对应月份 英文前三位
    public static String getEnglishMonthName(int month) {
        // 创建 DateFormatSymbols 对象，指定 Locale 为英文
        DateFormatSymbols dfs = new DateFormatSymbols(Locale.ENGLISH);

        // 获取月份的英文名称数组
        String[] monthNames = dfs.getMonths();

        // 由于月份从 0 开始计数，所以需要将获取的月份值减 1
        int adjustedMonth = month - 1;

        // 获取对应月份的英文名称
        String englishMonthName = monthNames[adjustedMonth];
        // 只获取前三个字母
        englishMonthName = englishMonthName.substring(0, 3);

        return englishMonthName;
    }
    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-01-08
     * @Param gpCtnOrder
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('ctn:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult<GpCtnOrderVo> getInfo(@PathVariable("id") Long id) {
        GpCtnOrder gpCtnOrder = iGpCtnOrderService.getById(id);
        GpCtnOrderVo gpCtnOrderVo = Convert.convert(new TypeReference<GpCtnOrderVo>() {
        }, gpCtnOrder);
        gpCtnOrderVo.setLoadedPicturesVo(StringUtils.stringToList(gpCtnOrder.getLoadedPictures()));
        gpCtnOrderVo.setLoadedVideoVo(StringUtils.stringToList(gpCtnOrder.getLoadedVideo()));
        return AjaxResult.success(gpCtnOrderVo);
    }


    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-01-08
     * @Param gpCtnOrder
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('ctn:order:remove')")
    @Log(title = "删除定货柜填写", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            GpCtnOrder gpCtnOrder = iGpCtnOrderService.getById(id);
            iGpPackagesInformationService.update(new UpdateWrapper<GpPackagesInformation>().set("ctn_order_id", null).set("send_status", null).set("nigeria_release_date", null).set("release_customer", null).set("release_customer_tel", null).set("sms_to_market_date", null).eq("ctn_order_id", gpCtnOrder.getId()));
            iGpSackInformationService.update(new UpdateWrapper<GpSackInformation>().set("ctn_order_id", null).set("send_status", null).set("nigeria_release_date", null).set("release_customer", null).set("release_customer_tel", null).set("sms_to_market_date", null).eq("ctn_order_id", gpCtnOrder.getId()));
        }
        return toAjax(iGpCtnOrderService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


}
